<?php
namespace Admin\Controller;
use Admin\Controller\ComController;
use Vendor\Tree;

class ProGardenController extends ComController {

	public function index(){
	
        $progarden = M('progarden')->field('id,pid,name,o')->order('o asc')->select();
		$progarden = $this->getMenu($progarden);
		$this->assign('progarden',$progarden);	
		$this -> display();
	}
	
	public function del(){
		//从地址栏获取要删除的新闻的id,如果没有，id=false
		$id = isset($_GET['id'])?intval($_GET['id']):false;
		if($id)
		{
			$data['id'] = $id;
			$progarden = M('progarden');
			if($progarden->where('pid='.$id)->count())
			{
				die('2');//存在子类，严禁删除。
			}else
			{
				$progarden->where('id='.$id)->delete();
				addlog('删除产品分类，ID：'.$id);
			}
			die('1');
		}else{
			die('0');
		}
	}
	
	public function edit(){
		//显示旧的产品分类的信息
		$id = isset($_GET['id'])?intval($_GET['id']):false;
		$currentcategory = M('progarden')->where('id='.$id)->find();
		$this->assign('cprogarden',$currentcategory);		
		
		//旧的产品分类的父亲
		$progarden = M('progarden')->field('id,pid,name')->order('o asc')->select();
		$tree = new Tree($progarden);
		$str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
		$progarden = $tree->get_tree(0,$str, $currentcategory['pid']);
		$this->assign('progarden',$progarden);
		
		$this->display();
	}
	
	public function add(){
		//在新增页面，下拉列表显示所有的分类 形成树形结构的分类
		$pid = isset($_GET['pid'])?intval($_GET['pid']):0;
		$progarden = M('progarden')->field('id,pid,name')->order('o asc')->select();
		$tree = new Tree($progarden);
		$str = "<option value=\$id \$selected>\$spacer\$name</option>"; //生成的形式
		$progarden = $tree->get_tree(0,$str, $pid);
		$this->assign('progarden',$progarden);
		
		$this -> display();
	}
	
	public function update(){
		//收集用户输入的数据		
		$id = isset($_POST['id'])?intval($_POST['id']):false;
		$data['pid'] = isset($_POST['pid'])?intval($_POST['pid']):0;
		$data['name'] = isset($_POST['name'])?trim($_POST['name']):false;
		$data['keywords'] = isset($_POST['keywords'])?strip_tags(trim($_POST['keywords'])):'';
		$data['description'] = isset($_POST['description'])?strip_tags(trim($_POST['description'])):'';
		$data['o'] = isset($_POST['o'])?intval($_POST['o']):0;
		//验证数据
		if(!$data['name']){
			die('0');
		}
		//根据提交有没有id,确认是修改还是增加
		if($id){
			//修改
			if(M('progarden')->data($data)->where('id='.$id)->save()){
				addlog('产品分类修改，ID：'.$id.'，名称：'.$name);
				die('1');
			}
		}
		else{
			//新增
			$id = M('progarden')->data($data)->add();
			if($id){
				addlog('新增产品分类，ID：'.$id.'，名称：'.$data['name']);
				die('1');
			}
		}
		die('0');
		
	}
}